package com.ljy.my_study.io.NIO.client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

import com.ljy.my_study.io.NIO.server.BufferCarrier;

/** 
* @author James
* @date 2018年11月5日 
*/
public class Client {
	
	public static void main(String[] args) throws IOException, InterruptedException {
		Scanner scanner=new Scanner(System.in);
		Charset utf8 = Charset.forName("UTF-8");
		SocketChannel channel=SocketChannel.open();
		channel.configureBlocking(false);
		Selector selector=Selector.open();
		channel.register(selector, SelectionKey.OP_READ|SelectionKey.OP_WRITE, new BufferCarrier(256,256));
		InetSocketAddress remoteAddress = new InetSocketAddress("127.0.0.1", 2333);
		channel.connect(remoteAddress);
		while(!channel.finishConnect()) {
			;
		}
		while(!Thread.currentThread().isInterrupted()) {
			int readyChannels=selector.select();
			if(readyChannels==0) {
				continue;
			}
			Set<SelectionKey> keys=selector.selectedKeys();
			Iterator<SelectionKey> it=keys.iterator();
			while(it.hasNext()) {
				SelectionKey k=it.next();
				it.remove();
				BufferCarrier bc=(BufferCarrier) k.attachment();
				ByteBuffer rb=bc.getReadBuffer();
				ByteBuffer wb=bc.getWriteBuffer();
				
				SocketChannel socketChannel=(SocketChannel) k.channel();
				
				if(k.isValid()&&k.isReadable()) {
					rb.clear();
					socketChannel.read(rb);
					rb.flip();
					CharBuffer cb = utf8.decode(rb);
					System.out.print("客户端接收到：");
                    System.out.println(cb.array());
					rb.clear();
				}
				if(k.isValid()&&k.isWritable()) {
//					String writeContent="write"+System.currentTimeMillis()+scanner.nextLine();
					String writeContent="write"+System.currentTimeMillis();
					System.out.println("客户端发送："+writeContent);
					wb.clear();
					wb.put(("客户端发送："+writeContent).getBytes());
					wb.flip();
					socketChannel.write(wb);
					wb.clear();
				}
			}
			Thread.sleep(800);
		}
	}
}
